import { defineStore } from "pinia";
import { MusicInfoOutput, PlaylistOutput, UserInfoOutput } from "../api";
import { ref } from "vue";

export const useStore = defineStore(
  "index",
  () => {
    const userInfo = ref<UserInfoOutput>();
    const audios = ref<Audio[]>([]);
    const curPlaylist = ref<PlaylistOutput>();

    const setUserInfo = (u: UserInfoOutput) => {
      userInfo.value = u;
    };
    const setCurPlaylist = (value: PlaylistOutput | undefined) => {
      curPlaylist.value = value;
    };
    const setAudios = (musicList: MusicInfoOutput[]) => {
      audios.value = musicList.map((music) => {
        return {
          name: music.title,
          artist: music.artist,
          url: music.filePath,
          cover: music.coverPath,
          lrc: music.lyricsPath,
        };
      });
      const aPlayer = window["aPlayer" as any] as any;
      aPlayer.list.clear();
      aPlayer.list.add(audios.value);
      if (aPlayer.paused) {
        aPlayer.play();
      }
    };

    const insertPlayer = (musicInfo: MusicInfoOutput) => {
      const aPlayer = window["aPlayer" as any] as any;
      const i = audios.value.findIndex(
        (e) => e.name == musicInfo.title && e.artist == musicInfo.artist
      );
      if (i >= 0) {
        aPlayer.list.switch(i);
      } else {
        const index = aPlayer.list.index;
        audios.value.splice(index, 0, {
          name: musicInfo.title,
          artist: musicInfo.artist,
          url: musicInfo.filePath,
          cover: musicInfo.coverPath,
          lrc: musicInfo.lyricsPath,
        });
        aPlayer.list.clear();
        aPlayer.list.add(audios.value);
        aPlayer.list.switch(index);
        if (aPlayer.paused) {
          aPlayer.play();
        }
      }
    };
    const clear = () => {
      userInfo.value = undefined;
      audios.value = [];
      curPlaylist.value = undefined;
    };

    return {
      userInfo,
      curPlaylist,
      audios,
      setUserInfo,
      setAudios,
      insertPlayer,
      setCurPlaylist,
      clear,
    };
  },
  {
    persist: true,
  }
);
